import {
	validatenull
} from '@/util/validate'

const keyName = 'ayy-'
/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
	const {
		content,
		type
	} = params
	const name = keyName + params.name
	const obj = {
		dataType: typeof(content),
		content: content,
		type: type,
		datetime: new Date().getTime()
	}

	const sObj = {
		key: name,
		data: JSON.stringify(obj)
	}

	uni.setStorage(sObj);
}
/**
 * 获取localStorage
 */

export const getStore = (params = {}) => {
	const name = keyName + params.name
	const debug = params.debug
	let obj = {}
	let content
	uni.getStorage({
		key: name,
		success: function(res) {
			obj = res.data
		}
	});
	if (validatenull(obj)) {
		uni.getStorage({
			key: name,
			success: function(res) {
				obj = res.data
			}
		});
	}
	if (validatenull(obj)) return
	try {
		obj = JSON.parse(obj)
	} catch (e) {
		return obj
	}
	if (debug) {
		return obj
	}
	if (obj.dataType === 'string') {
		content = obj.content
	} else if (obj.dataType === 'number') {
		content = Number(obj.content)
	} else if (obj.dataType === 'boolean') {
		content = eval(obj.content)
	} else if (obj.dataType === 'object') {
		content = obj.content
	}
	return content
}
/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
	const name = keyName + params.name
	const type = params.type
	
	uni.removeStorage({
		key: name,
		success: function (res) {
			console.log('success');
		}
	});
}

/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
	const {
		type
	} = params
	try {
		uni.clearStorage();
	} catch (e) {
		// error
	}
}